package com.eipc;


import org.androidpn.sdk.Constants;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import com.eipc.model.ImportNotice;
import com.eipc.model.SerInfoResponse;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.JsonParse;
import com.eipc.util.MyLog;
import com.eipc.util.Tools;

public class FetchNoticeService extends Service {
	private DBHelper mDB;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		mDB = new DBHelper(this);
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		new PollingTask().execute();
		Log.e("-----------do FetchNoticeService-----------------",Tools.getCurrentTimeString());
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	class PollingTask extends AsyncTask<Void, Void, Void>{
		private String mResult;
		@Override
		protected Void doInBackground(Void... params) {
			try {
				SharedPreferences sdkPreferences = getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
				String mobileID = sdkPreferences.getString(Constants.XMPP_USERNAME,"");
				String maxID    = sdkPreferences.getString(Constants.MaxId,"0");
				String ids = mDB.getIDs();
				mResult = HttpManager.polling(getString(R.string.url_polling),Constants.TTYPE_NOTICE,maxID,ids,mobileID,"0");
				Log.e("------------refesh notices-------------",String.valueOf(mResult));
				if(mResult!=null && !"".equals(mResult)){
					SerInfoResponse resp = JsonParse.parseSerInfoResponse(mResult,Constants.LOAD_INPORTNOTICE);
					if(resp!=null&&resp.success&&resp.os!=null&&resp.os.length>0){
						if(resp.id!=null&&!"".equals(resp.id)){
							mDB.updateMaxId(resp.id);
							try{mDB.insertImportNotice((ImportNotice[])resp.os,resp.id);}catch(Exception e){}
						}
					}else{
							Log.e(this.getClass().getName()+" polling failure : ",resp.toString());
					}
				}else{
					Log.e(this.getClass().getName()+" polling failure : ","mResult is null");
				}
			} catch (Exception e) {
				MyLog.error(FetchConsultService.class,"",e);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			
		}
		
	}
}
